﻿using UnityEngine;
using LuaInterface;

namespace Framework
{
	public class GameState : MonoSingleton<GameState>
	{
		public static volatile bool isRunning;
		public static volatile bool isFront;
        public static volatile int screenWidth;
        public static volatile int screenHeight;

		void Awake()
		{
			isFront = true;
			isRunning = true;
            screenWidth = Screen.width;
            screenHeight = Screen.height;
        }

		private GeneralCallBack _pauseCallback;
		private GeneralCallBack _lowMemoryCallback;

		public void SetApplicationPauseCallback(LuaFunction luaCb, LuaTable luaCbObj)
		{
			GeneralCallBack.GetOrReUse(ref _pauseCallback, luaCb, luaCbObj);
		}

		public void SetApplicationLowMemoryCallback(LuaFunction luaCb, LuaTable luaCbObj)
		{
			if (luaCb != null)
			{
				if (_lowMemoryCallback == null)
				{
					Application.lowMemory += LowMemoryCall;
				}
				GeneralCallBack.GetOrReUse(ref _lowMemoryCallback, luaCb, luaCbObj);
			}
			else
			{
				Application.lowMemory -= LowMemoryCall;
				GeneralCallBack.RecycleInst(ref _lowMemoryCallback);
			}
		}


		private void LowMemoryCall()
		{
			GeneralCallBack.Invoke(ref _lowMemoryCallback);
		}

		void OnApplicationPause(bool pause)
		{
			if (!isRunning)
				return;
			isFront = !pause;
			Logger.Log("GameState isFront = " + isFront);

			if (null != _pauseCallback)
            {
				GeneralCallBack.Invoke(ref _pauseCallback, isFront);
            }
		}

		void OnApplicationQuit()
		{
			isRunning = false;
			// try
			// {
			// 	SocketMgr.Instance.Dispose();
			// }
			// catch (System.Exception e)
			// {
			// 	Logger.LogWarning(e);
			// }
		}
	}
}
